/**
 * Created by sail on 2017/6/1.
 */
import WeCropper from './common/we-cropper.js'
import CONFIG from './common/config'
import httpConfig from './httpConfig'
const config = new CONFIG()
config.init()
const app = getApp()
const device = wx.getSystemInfoSync()
const width = device.windowWidth
const height = device.windowHeight - 90 - device.statusBarHeight
var CryptoJS = require("crypto-js");
Page({
  data: {
    cropperOpt: {
      id: 'cropper',
      targetId: 'targetCropper',
      pixelRatio: device.pixelRatio,
      width,
      height,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - 300) / 2,
        y: (height - 300) / 2,
        width: 300,
        height: 300
      },
      boundStyle: {
        color: config.getThemeColor(),
        mask: 'rgba(0,0,0,0.8)',
        lineWidth: 1
      },
    }
  },
  onLoad: function(options){
    if (options.imgUrl) {
      this.cropper.pushOrign(imgUrl)
    }
  },
     /**
   * 生命周期函数--监听页面初次渲染完成
   */
  // onReady: function () {
  //   console.log(device)
  //   console.log(height)
  //   this.uploadTap()
  // },
  touchStart(e) {
    this.cropper.touchStart(e)
  },
  touchMove(e) {
    this.cropper.touchMove(e)
  },
  touchEnd(e) {
    this.cropper.touchEnd(e)
  },
  getCropperImage() {
    const fs = wx.getFileSystemManager()
    const _this = this
    this.cropper.getCropperImage()
      .then((src) => {
        console.log(src, 'src')
        // wx.previewImage({
        //   current: '', // 当前显示图片的http链接
        //   urls: [src] // 需要预览的图片http链接列表
        // })
        fs.readFile({
          filePath: src,
          encoding: "base64",
          success: (file) => {
            console.log(file, 'file')
            this.handleImage('data:image/png;base64,' + file.data)
          }
        })
      })
      .catch((err) => {
        wx.showModal({
          title: '温馨提示',
          content: err.message
        })
      })
  },
  /**
   * 图片解析成地址
   * @param {} image 
   */
  handleImage(image) {
    var appId =  httpConfig.appId;
    var method = httpConfig.method;
    var ts = Date.now();
    var appKey = httpConfig.appKey;
    // 计算签名
    var signStr = appId + method + ts + appKey;
    var sign = CryptoJS.MD5(signStr).toString()
    // formData
    const param = {
      app_id: appId,
      method: method,
      ts: ts,
      sign: sign,
      data: JSON.stringify({
        image
      }),
    }
    wx.showLoading({
      title: '识别中',
    })
    wx.request({
      url: httpConfig.url,
      header: {
        'cache-control': 'no-cache',
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: param,
      method: 'POST',
      success: (res) => {
        wx.hideLoading()
        console.log(res, 'res')
        if (res.data.code == 0) {
          this.setData({
            content: res.data.data.original
          })
          const pages = getCurrentPages();
          const prevPage = pages[pages.length - 2];
          let data = res.data.data;
          let result = {};
          // result.province_name = data.detail.province;
          // result.city_name = data.detail.city;
          // result.county_name = data.detail.district;
          // result.name = data.name;
          // result.mobile = data.mobile;
          // result.town_name = data.detail.town_name;
          // result.detail = data.detail.address;
          result.province_name = data.province_name;
          result.city_name = data.city_name;
          result.county_name = data.county_name;
          result.name = data.name;
          result.mobile = data.mobile;
          result.town_name = data.town_name;
          result.detail = data.detail;
          prevPage.setRecipient(result)
          wx.navigateBack(-1)
        }else{
          wx.showToast({
            title: '图片识别失败,请更换图片',
            icon: 'none'
          })
        }
      },
      fail: function (err) {
        wx.hideLoading()
        console.log(err, 'err')
      }
    })

  },
  uploadTap() {
    const self = this
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        console.log(res, 'res')
        const src = res.tempFilePaths[0]
        //  获取裁剪图片资源后，给data添加src属性及其值
        self.cropper.pushOrign(src)
      }
    })
  },
  onLoad(option) {
    const {
      cropperOpt
    } = this.data

    cropperOpt.boundStyle.color = config.getThemeColor()

    this.setData({
      cropperOpt
    })

    this.cropper = new WeCropper(cropperOpt)
      .on('ready', (ctx) => {
        console.log(`wecropper is ready for work!`)
        if (option.imgUrl) {
          ctx.pushOrign(option.imgUrl)
        }
      })
      .on('beforeImageLoad', (ctx) => {
        wx.showToast({
          title: '上传中',
          icon: 'loading',
          duration: 20000
        })
      })
      .on('imageLoad', (ctx) => {
        wx.hideToast()
      })
  },
  cancelTap(){
    wx.navigateBack(-1)
  }
})